﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinnesLayer.LogicBusiness;
using System.Data;
using System.ComponentModel;
using EntitiesLayer.Entities;
using Microsoft.Reporting.WebForms;

namespace ClinicaSanPablo.reportes
{
    public partial class DescargarReporte : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {

                    string codigoSolicitud = Request.QueryString["codigoSolicitud"] ?? "";
                    string descripcionSolicitud = Request.QueryString["descripcionSolicitud"] ?? "";
                    string estadoSolicitud = Request.QueryString["estadoSolicitud"] ?? "";
                    string usuarioRegistro = Request.QueryString["usuarioRegistro"] ?? "";
                    string areaRegistro = Request.QueryString["areaRegistro"] ?? "";
                    string areaInvolucrada = Request.QueryString["areaInvolucrada"] ?? "";
                    string servicioInvolucrado = Request.QueryString["servicioInvolucrado"] ?? "";
                    string formaPresentacion = Request.QueryString["formaPresentacion"] ?? "";
                    string fecha = Request.QueryString["fecha"] ?? "";



                    Solicitudbl solBl = new Solicitudbl();
                    List<Solicitud> lista = solBl.ConsultarSolicitud(codigoSolicitud, descripcionSolicitud, estadoSolicitud, usuarioRegistro, areaRegistro, areaInvolucrada, servicioInvolucrado, fecha, formaPresentacion);

                    DataTable ds = ConvertTo(lista);

                    //...
                    ReportViewer1.ProcessingMode = ProcessingMode.Local;
                    ReportDataSource datasource = new ReportDataSource("DsReporteGeneral", ds);
                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(datasource);

                    List<EntidadUtil> reg = new List<EntidadUtil>();
                    reg.Add(new EntidadUtil() { NroRegistros = lista.Count.ToString() });
                    ReportDataSource datasource2 = new ReportDataSource("DTTmp", ConvertTo(reg));
                    ReportViewer1.LocalReport.DataSources.Add(datasource2);

                    ReportViewer1.LocalReport.ReportPath = "reportes/ReporteHistoricoSolicitudes.rdlc";
                    ReportViewer1.LocalReport.Refresh();
                    ReportViewer1.DataBind();
                    AbrirPDF();
                }
            }
            catch(Exception ex)
            { }
        }
        public void AbrirPDF()
        {
            string mimeType;
            string encoding;
            string fileNameExtension;
         
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = ReportViewer1.LocalReport.Render(
                "pdf",
                null,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-disposition", "attachment; filename=Listado.pdf");
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }
        // this is the method I have been using 
        public static DataTable ConvertTo<T>(IList<T> list)
        {
            DataTable table = CreateTable<T>();
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (T item in list)
            {
                DataRow row = table.NewRow();

                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item);
                }

                table.Rows.Add(row);
            }

            return table;
        }
        public static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            DataTable table = new DataTable(entityType.Name);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (PropertyDescriptor prop in properties)
            {
                // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES 
                table.Columns.Add(prop.Name, prop.PropertyType);
            }

            return table;
        }

    }

    public class EntidadUtil
    {
        public String NroRegistros { get; set; }
    }
}